package com.kkb.service.impl;

import com.kkb.domain.AjaxResult;
import com.kkb.mapper.TbSpecMapper;
import com.kkb.mapper.TbSpecOptionMapper;
import com.kkb.pojo.TbSpec;
import com.kkb.pojo.TbSpecExample;
import com.kkb.pojo.TbSpecOption;
import com.kkb.pojo.TbSpecOptionExample;
import com.kkb.service.TbSpecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
@Service
public class TbSpecServiceImpl implements TbSpecService {
    @Autowired
    private TbSpecMapper tbSpecMapper;

    @Autowired
    private TbSpecOptionMapper tbSpecOptionMapper;

    @Override
    public List<TbSpec> querySpecList() {
        TbSpecExample example = new TbSpecExample();
        List<TbSpec> tbSpecList=tbSpecMapper.selectByExample(example);

        //查询每一个specId下对应的选项，封装到specList中
        for (TbSpec tbSpec : tbSpecList) {
            TbSpecOptionExample optionExample = new TbSpecOptionExample();
            TbSpecOptionExample.Criteria criteria = optionExample.createCriteria();
            criteria.andSpecIdEqualTo(tbSpec.getSpecId());
            List<TbSpecOption> tbSpecOptions = tbSpecOptionMapper.selectByExample(optionExample);
            tbSpec.setSpecOptionList(tbSpecOptions);
        }
        return tbSpecList;
    }

    @Override
    @Transactional
    public AjaxResult addSpecAndOption(TbSpec tbSpec) {
        //先查询一级规格名称是否存在，存在则只根据specID存option表的，
        TbSpecExample specExample = new TbSpecExample();
        TbSpecExample.Criteria criteria = specExample.createCriteria();
        criteria.andSpecNameEqualTo(tbSpec.getSpecName());
        List<TbSpec> tbSpecList = tbSpecMapper.selectByExample(specExample);
        Integer specId;
        if(tbSpecList.isEmpty()){
            tbSpec.setCreateTime(new Date());
            tbSpec.setStatus("1");
            tbSpec.setIsDelete("N");
            //插入规格表中
            tbSpecMapper.insert(tbSpec);
            //查出刚刚插入数据库中specId供后面存入选项时关联使用
            List<TbSpec> specList = tbSpecMapper.selectByExample(specExample);
             specId= specList.get(0).getSpecId();
        }else {
            //查出数据库中specId供后面存入选项时关联使用
            specId= tbSpecList.get(0).getSpecId();
        }

        List<TbSpecOption> specOptionList = tbSpec.getSpecOptionList();
        if(specOptionList.isEmpty()){
            return AjaxResult.error();
        }

        //插入规格选项表中
        for (TbSpecOption tbSpecOption : specOptionList) {
            tbSpecOption.setCreateTime(new Date());
            //通过规格id相关联
            tbSpecOption.setSpecId(specId);
            tbSpecOption.setStatus("1");
            tbSpecOption.setIsDelete("N");
            int result = tbSpecOptionMapper.insert(tbSpecOption);
        }
        return AjaxResult.success();
    }
}
